package com.zhangyujun.bysj.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.zhangyujun.bysj.manager.service.ValidateCodeService;
import com.zhangyujun.bysj.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //生成验证码
    @Override
    public ValidateCodeVo generateValidateCode() {
        //1 通过工具生成图片验证码
        //宽度 高度 验证码位数  干扰线条数
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 10);
        //获取验证码值
        String codeValue = circleCaptcha.getCode();
        //获取验证码图片base64值
        String imageBase64 = circleCaptcha.getImageBase64();
        //2 将验证码存入redis里面 设置redis的key：UUID value:验证码值
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("user:validate" + key,
                codeValue, 5, TimeUnit.MINUTES);
        //设置过期时间
        //3 返回VaildateCodeVo对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        //redis存储的key
        validateCodeVo.setCodeKey(key);
        //此处放的是图片的base64值返回
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);
        return validateCodeVo;
    }
}
